﻿

using Newtonsoft.Json;
using System.Reflection.Metadata.Ecma335;

namespace Main.api.midiwhere
{
    /// <summary>
    /// 请求中间件
    /// </summary>
    public class RequestMiddleware : IMiddleware
    {
        /// <summary>
        /// 请求中间件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                await next.Invoke(context);
            }
            catch (Exception ex)
            {
                var result = JsonConvert.SerializeObject(new
                {
                    code = 500,
                    msg = ex.Message
                });
                await context.Response.WriteAsync(result);
            }
            finally
            {
                context.Response.OnCompleted(() =>
                {
                    return Task.CompletedTask;
                });
            }
        }
    }
}
